/**
 * 图片模块服务文件
 */

const db = require('../db/picture');
const path = require('path');
const fs = require('fs');
const folder = path.resolve(__dirname, '../static/goods');  //商品图片保存文件夹

/**
 * 保存文件
 * @param {*} file 要保存的文件
 */
const saveFile = (file) => {
    return new Promise((resolve, reject) => {
        const { filepath, newFilename, originalFilename } = file;
        if (!fs.existsSync(folder)) {
            fs.mkdirSync(folder);
        }
        const read = fs.createReadStream(filepath); //创建读取流，读取上传的临时文件
        const ext = '.' + originalFilename.split('.').pop();
        const newFilePath = path.join(folder, newFilename + ext);    //新的文件路径
        const write = fs.createWriteStream(newFilePath);   //创建写入流
        read.pipe(write);
        write.on('close', () => {
            read.destroy();
            write.destroy();
            resolve(newFilename + ext);
        });
        write.on('error', () => {
            reject();
        });
    });
}

/**
 * 添加
 * @param {*} ctx 
 */
const add = async ctx => {
    try {
        const files = [];
        for (const key in ctx.request.files) {
            const file = ctx.request.files[key];
            const { mimetype } = (file || {});
            try {
                if (!/^image\/.+/.test(mimetype)) {
                    continue;
                }
                const fileName = await saveFile(file);
                files.push({ user_id: ctx.state.user.id, name: fileName });
            } catch (error) {
                ctx.app.emit('error', error);
            }
        }
        if (!files.length) {
            throw 1;
        }
        //保存
        await db.add(files);
        ctx.body = {
            code: 1,
            msg: '图片上传成功'
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.status = 500;
    }
}

/**
 * 删除
 * @param {*} ctx 
 */
const del = async ctx => {
    try {
        const { id } = ctx.request.params;
        await db.del(id);
        ctx.body = {
            code: 1,
            msg: '图片删除成功'
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '图片删除失败'
        }
    }
}

/**
 * 获取
 * @param {*} ctx 
 */
const getAll = async ctx => {
    try {
        const { query } = ctx.request;
        query.user_id = ctx.state.user.id;
        const { rows, count } = await db.getAll(query);
        ctx.body = {
            code: 1,
            data: rows,
            count
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '图片获取失败'
        }
    }
}

module.exports = {
    add,
    del,
    getAll,
}